package com.android.semita;

import java.text.DecimalFormat;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.semita.controller.InvoiceController;
import com.android.semita.controller.ShippedLocationController;
import com.android.semita.model.Invoice;
import com.android.semita.model.ShippedLocationItem;

public class InvoiceDetailActivity extends Activity {
	private static String APIUrl = "http://202.21.149.53/SemitaServices/api/";
	protected static final int ACTIVITY_SHOW_MAP = 2;

	private InvoiceItemAdapter adapterInvoiceItemList;
	private ListView lvInvoiceItemList;

	private TextView tvTotalInvoiceItem;
	private TextView tvTotalInvoiceItemAmount;

	private TextView tvInvoiceNo;
	private TextView tvCustomerID;
	private TextView tvCustomerAddress;

	private String InvoiceNo = "";
	private String MessengerId = "";

	// private ArrayList<InvoiceItem> invoice_detail_list;
	private Invoice currentInvoice = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_invoice_detail);
		// Show the Up button in the action bar.
		setupActionBar();

		lvInvoiceItemList = (ListView) findViewById(R.id.lvInvoiceItemList);

		tvInvoiceNo = (TextView) findViewById(R.id.txtInvoiceNo);
		tvCustomerID = (TextView) findViewById(R.id.txtCustomerID);
		tvCustomerAddress = (TextView) findViewById(R.id.txtCustomerAddress);

		InvoiceNo = getIntent().getStringExtra("InvoiceNo"); // "SI-131100001";
		MessengerId = getIntent().getStringExtra("MessengerId"); // "1";

		// call AsyncTask for get JSON string
		new getJSONInvoiceItems(this).execute(InvoiceNo);

	}

	private void Summary(Float totalAmount) {
		Integer countInvoiceItem = currentInvoice.getInvoiceItems().size();

		tvTotalInvoiceItem = (TextView) findViewById(R.id.textview_count_invoice_item);
		tvTotalInvoiceItemAmount = (TextView) findViewById(R.id.textview_total_invoice_amount);

		if (tvTotalInvoiceItem != null) {
			tvTotalInvoiceItem.setText(countInvoiceItem.toString());
		}
		if (tvTotalInvoiceItemAmount != null) {
			tvTotalInvoiceItemAmount.setText(totalAmount.toString());
		}
	}

	// call back method for AsyncTask::getJSONInvoiceDetail()
	private void GetInvoiceItemsFromJSON(String JSONString,
			ProgressDialog dialog) {
		try {
			String jsonString = JSONString
					.substring(1, JSONString.length() - 1);
			currentInvoice = new InvoiceController()
					.getInvoiceFromJSON(jsonString);

			tvInvoiceNo.setText(currentInvoice.getInvoiceNo());
			tvCustomerID.setText("(" + currentInvoice.getCustomerId() + ")"
					+ currentInvoice.getCustomerName());
			tvCustomerAddress.setText(currentInvoice.getCustomerAddress());

			adapterInvoiceItemList = new InvoiceItemAdapter(this,
					R.layout.invoice_item_list, currentInvoice.Items);
			lvInvoiceItemList.setAdapter(adapterInvoiceItemList);

			Summary(currentInvoice.getInvoiceAmount());
		} finally {
			if (dialog.isShowing()) {
				dialog.dismiss();
			}
		}
	}

	// ///////////////////////////////////////////////////////////////////////////
	private class getJSONInvoiceItems extends
			AsyncTask<String, Integer, String> {
		private Context context;
		private ProgressDialog dialog;

		public getJSONInvoiceItems(InvoiceDetailActivity activity) {
			context = activity;
			dialog = new ProgressDialog(context);
			dialog.setCancelable(true);
		}

		@Override
		protected void onPreExecute() {
			this.dialog.setMessage("Waiting...");
			this.dialog.show();
		}

		@Override
		protected String doInBackground(String... InvoiceNo) {
			String returnJSONString = "";
			String invoiceNo = InvoiceNo[0];
			String RequestURL = APIUrl + "InvoiceDetail?invoice_no="
					+ invoiceNo;

			try {
				JSONParser jsonParser = new JSONParser();
				returnJSONString = jsonParser.getJSONFromUrl(RequestURL);

				returnJSONString = returnJSONString.replace("\\", "");
			} catch (Exception e) {
				e.printStackTrace();
			}

			return returnJSONString;
		}

		@Override
		protected void onProgressUpdate(Integer... values) {
		}

		@Override
		protected void onPostExecute(String JSONResult) {
			GetInvoiceItemsFromJSON(JSONResult, dialog);
		}
	}

	// ///////////////////////////////////////////////////////////////////////////

	private void ratingActionResult(boolean confirmSuccess, ProgressDialog dialog) {
		dialog.dismiss();

		String dialogMessage = "";

		if (confirmSuccess) {
			dialogMessage = "Update delivery status success.";
		} else {
			dialogMessage = "Update delivery status not success.";
		}

		new AlertDialog.Builder(this).setMessage(dialogMessage)
				.setCancelable(false)
				.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						finish();
					}
				}).show();

	}

	// ///////////////////////////////////////////////////////////////////////////
	private class ratingAndConfirmShipped extends
			AsyncTask<String, Integer, String> {
		private Context context;
		private ProgressDialog dialog;

		public ratingAndConfirmShipped(InvoiceDetailActivity activity) {
			context = activity;
			dialog = new ProgressDialog(context);
			dialog.setCancelable(true);
		}

		@Override
		protected void onPreExecute() {
			this.dialog.setMessage("Waiting...");
			this.dialog.show();
		}

		@Override
		protected String doInBackground(String... values) {
			String returnJSONString = "";
			//String feedbackScore = values[0];
			String location = values[1];
			String successFlag = values[2];
			String invoiceStatus = "Shipped";
			
			
			//in case of ship not success.
			if(successFlag.equalsIgnoreCase("0"))
			{
				invoiceStatus = "NotSuccess";
			}
			
			String RequestURL = APIUrl + "deliverytran?invoice_no=" + InvoiceNo
					+ "&invoice_status=" + invoiceStatus  //feedback_score=" + feedbackScore
					+ "&address_gps=" + location + 
					"&messenger_id=" + MessengerId;

			try {
				JSONParser jsonParser = new JSONParser();
				returnJSONString = jsonParser.getJSONFromUrl(RequestURL);

				returnJSONString = returnJSONString.replace("\\", "");
			} catch (Exception e) {
				e.printStackTrace();
			}

			return returnJSONString;
		}

		@Override
		protected void onProgressUpdate(Integer... values) {
		}

		@Override
		protected void onPostExecute(String JSONResult) {
			// replace double quote
			JSONResult = JSONResult.replace("\"", "");

			if (JSONResult.equalsIgnoreCase("true")) {
				ratingActionResult(true, dialog);
			} else {
				ratingActionResult(false, dialog);
			}

		}
	}

	// ///////////////////////////////////////////////////////////////////////////

	private void setupActionBar() {
		getActionBar().setDisplayHomeAsUpEnabled(true);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.invoice_detail, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			NavUtils.navigateUpFromSameTask(this);
			return true;
		case R.id.action_confirm:
			ShowConfirmShippedDialog(true);
			break;
		case R.id.action_show_map:
			// Call async task to get ShippedLocationItem 
			new getJSONShipLocation().execute(InvoiceNo);
			break;
		case R.id.action_not_shipped:
			// Call async task to get ShippedLocationItem 
			ShowConfirmShippedDialog(false);
			break;
		}

		return super.onOptionsItemSelected(item);
	}

	// call back method for AsyncTask::getJSONForInvoices()
	private void GetShipLocationFromJSON(String JSONString) {

		ShippedLocationController ship = new ShippedLocationController();

		ShippedLocationItem shipLocationItem = ship.getShippedLocationFromJSON(JSONString);

		if (shipLocationItem != null) {
			Intent intent_show_map = new Intent(this, LocationMapActivity.class);
			intent_show_map.putExtra(ShippedLocationItem.LATITUDE,shipLocationItem.getLatitude());
			intent_show_map.putExtra(ShippedLocationItem.LONGTITUDE,shipLocationItem.getLongitude());
			intent_show_map.putExtra(ShippedLocationItem.ADDRESS,shipLocationItem.getAddress());
			intent_show_map.putExtra(ShippedLocationItem.CUSTOMERNAME,shipLocationItem.getCustomerName());
			intent_show_map.putExtra(ShippedLocationItem.INVOICE_NO,shipLocationItem.getInvoiceNo());
			
			
			startActivityForResult(intent_show_map, ACTIVITY_SHOW_MAP);
		} else {
			alert("GPS location not found");
		}

	}

	private void alert(String message) {
		Toast.makeText(this, message, Toast.LENGTH_LONG).show();
	}

	// ///////////////////Start Async Task for get Location ////////////////////////////////////////////////////////
	private class getJSONShipLocation extends
			AsyncTask<String, Integer, String> {
		@Override
		protected void onPreExecute() {

		}

		@Override
		protected String doInBackground(String... request) {
			String returnJSONString = "";
			String RequestURL = "http://202.21.149.53/SemitaServices/api/shippedlocation?invoice_no=" + request[0]; 	 
			
			try {
				JSONParser jsonParser = new JSONParser();
				returnJSONString = jsonParser.getJSONFromUrl(RequestURL);

				//Replace Json String location "\" 
				returnJSONString = returnJSONString.replace("\\", "");
				
				returnJSONString = returnJSONString.substring(1, returnJSONString.length() - 1);

			 
			} catch (Exception e) {
				e.printStackTrace();
			}

			return returnJSONString;
		}

		@Override
		protected void onProgressUpdate(Integer... values) {
		}

		@Override
		protected void onPostExecute(String JSONResult) {
			System.out
					.println("onPostExecute,Param. JSONResult: " + JSONResult);
			GetShipLocationFromJSON(JSONResult);
		}
	}

	/////////////////////////End Async Task for get Location ////////////////////////////////////////////////////
	
	
	 
	public void ShowConfirmShippedDialog(boolean IsSuccess) {
		final AlertDialog.Builder popDialog = new AlertDialog.Builder(this);
		/*final RatingBar rating = new RatingBar(this);
		rating.setMax(5);
		rating.setNumStars(5);
		rating.setStepSize(1f);
		rating.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
				LayoutParams.WRAP_CONTENT));
		LinearLayout parent = new LinearLayout(InvoiceDetailActivity.this);

		parent.setGravity(Gravity.CENTER);
		parent.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
				LayoutParams.MATCH_PARENT));
		parent.addView(rating);*/

		//popDialog.setIcon(android.R.drawable.btn_star_big_on);
		
		if(IsSuccess)
		{
			popDialog.setTitle("Confirm");
			popDialog.setMessage("Please confirm shipped Success.");
		}
		else
		{
			popDialog.setTitle("Confirm");
			popDialog.setMessage("Please confirm not shipped.");
		}
		
		//popDialog.setView(parent);

		// Button OK
		if(IsSuccess){
			popDialog.setPositiveButton("Confirm",
					new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {					 
							String score ="" ;  
							UpdateFeedbackScoreAndUpdateStatus(score,true);
							dialog.dismiss();
						}
					})

			// Button Cancel
					.setNegativeButton("Cancel",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog, int id) {
									dialog.cancel();
								}
							});

			popDialog.create();
			popDialog.show();		
		}
		else
		{
			popDialog.setPositiveButton("Confirm",
					new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {					 
							String score ="" ;  
							UpdateFeedbackScoreAndUpdateStatus(score,false);
							dialog.dismiss();
						}
					})

			// Button Cancel
					.setNegativeButton("Cancel",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog, int id) {
									dialog.cancel();
								}
							});

			popDialog.create();
			popDialog.show();		
		}


	}

	private void UpdateFeedbackScoreAndUpdateStatus(String Score, boolean IsSuccess) {
		String location = getLocationString();

		// call asyncTask for update status and rating
		if(IsSuccess)
		{
			new ratingAndConfirmShipped(this).execute(Score, location, "1");
		}
		else
		{
			new ratingAndConfirmShipped(this).execute(Score, location, "0");
		}
			

		
	}

	private String getLocationString() {
		DecimalFormat decimalFormat = new DecimalFormat("#.00000");

		Location location = getCurrentLocation();
		String locationString = "";

		if (location != null) {
			locationString = decimalFormat.format(location.getLatitude()) + ","
					+ decimalFormat.format(location.getLongitude());
		}

		return locationString;
	}

	private Location getCurrentLocation() {
		LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		List<String> providers = manager.getAllProviders();
		for (String provider : providers)
			if (manager.isProviderEnabled(provider)) {
				Location loc = manager.getLastKnownLocation(provider);
				return loc;
			}

		return null;
	}
}
